package com.telenav.module.user;

import java.util.ArrayList;
import java.util.List;

import org.jivesoftware.smack.Chat;
import org.jivesoftware.smack.ChatManager;
import org.jivesoftware.smack.ChatManagerListener;
import org.jivesoftware.smack.MessageListener;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.packet.Message;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.SpannableString;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.telenav.app.R;
import com.telenav.app.widget.ActionBar;
import com.telenav.app.widget.ActionBar.Action;
import com.telenav.app.widget.ActionBar.IntentAction;
import com.telenav.data.dao.AccountDao;
import com.telenav.data.dao.MessagesDao;
import com.telenav.module.city.CityActivity;
import com.telenav.module.entity.MessageEntity;
import com.telenav.util.SmileysUtil;
import com.telenav.xmpp.TimeRender;
import com.telenav.xmpp.XmppTool;

public class ChatActivity extends Activity {

	private MyAdapter adapter;
	private List<MessageEntity> listMsg = new ArrayList();
	private String pUSERID;
	private String mUserName;
	private EditText msgText;
	private ProgressBar pb;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.formclient);
		this.pUSERID = getIntent().getStringExtra("user");
		this.mUserName = getIntent().getStringExtra("alias");
		ListView listview = (ListView) findViewById(R.id.formclient_listview);
		listview.setTranscriptMode(ListView.TRANSCRIPT_MODE_ALWAYS_SCROLL);
		listMsg = MessagesDao.getInstance().getMessage(1000);
		this.adapter = new MyAdapter(this, listMsg);
		listview.setAdapter(adapter);
		this.msgText = (EditText) findViewById(R.id.formclient_text);
		this.pb = (ProgressBar) findViewById(R.id.formclient_pb);

		SmileysUtil.init(this);
		
		//message listener
		ChatManager cm = XmppTool.getConnection().getChatManager();
		final Chat newchat = cm.createChat(pUSERID, null);
		cm.addChatListener(new ChatManagerListener() {
			@Override
			public void chatCreated(Chat chat, boolean able) {
				chat.addMessageListener(new MessageListener() {
					@Override
					public void processMessage(Chat chat2, Message message) {
						String[] args = new String[] {mUserName, message.getBody(), TimeRender.getDate(), "IN" };
						android.os.Message msg = handler.obtainMessage();
						msg.what = 1;
						msg.obj = args;
						msg.sendToTarget();
					}
				});
			}
		});
		
		final String user = AccountDao.getInstance().getAccountName();
		//send message
		Button btsend = (Button) findViewById(R.id.formclient_btsend);
		btsend.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				String msg = msgText.getText().toString();
				if(msg.length() > 0){
					listMsg.add(new MessageEntity(user, msg, TimeRender.getDate(), "OUT"));
					adapter.notifyDataSetChanged();
					try {
						newchat.sendMessage(msg);
					} catch (XMPPException e) {
						e.printStackTrace();
					}
				}
				msgText.setText("");
			}
		});
		
		ActionBar actionBar = (ActionBar) findViewById(R.id.actionbar);
		actionBar.setTitle(mUserName);
		
		actionBar.addLeftAction(new IntentAction(this, new Intent(ChatActivity.this, FriendListActivity.class), R.drawable.yy_action_bar_back));
		actionBar.setBackEnabled(true);
		
		Intent intent = new Intent(ChatActivity.this, PersonalInfoActivity.class);
		intent.putExtra("username", pUSERID);
		final Action otherAction = new IntentAction(this, intent, R.drawable.yy_action_bar_location);
        actionBar.addRightAction(otherAction);
		
		final SimileImageAdapter adapter = new SimileImageAdapter(this);
		ImageButton simileImage = (ImageButton) findViewById(R.id.simileImage);
		simileImage.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				GridView girdView = (GridView) findViewById(R.id.similegridView);
				int flag = girdView.getVisibility();
				if(flag != View.VISIBLE)
				{
					girdView.setVisibility(View.VISIBLE);
					girdView.setAdapter(adapter);
					girdView.setOnItemClickListener(listener);
				}
				else
				{
					girdView.setVisibility(View.GONE);
				}
			}
		});
	}

	private AdapterView.OnItemClickListener listener = new AdapterView.OnItemClickListener() {
		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {
			String text = msgText.getText().toString() + SmileysUtil.getInstance().getSmileyText(position);
			SpannableString spanStr  = SmileysUtil.getInstance().getSmileSpan(text);
	        msgText.setText(spanStr);
		}
	};
	
	private Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case 1:
				String[] args = (String[]) msg.obj;
				listMsg.add(new MessageEntity(args[0], args[1], args[2], args[3]));
				adapter.notifyDataSetChanged();
				break;
			default:
				break;
			}
		};
	};

	class MyAdapter extends BaseAdapter {

		private Context cxt;
		private LayoutInflater inflater;
		
		private List<MessageEntity> msgs;

		public MyAdapter(ChatActivity formClient, List<MessageEntity> listMsg ) {
			this.cxt = formClient;
			this.msgs = listMsg;
		}

		@Override
		public int getCount() {
			return msgs.size();
		}

		@Override
		public Object getItem(int position) {
			return msgs.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			this.inflater = (LayoutInflater) this.cxt.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			if(msgs.get(position).getFrom().equals("IN")){
				convertView = this.inflater.inflate(R.layout.formclient_chat_in, null);
			}else{
				convertView = this.inflater.inflate(R.layout.formclient_chat_out, null);
			}
			TextView useridView = (TextView) convertView.findViewById(R.id.formclient_row_userid);
			TextView dateView = (TextView) convertView.findViewById(R.id.formclient_row_date);
			TextView msgView = (TextView) convertView.findViewById(R.id.formclient_row_msg);
			useridView.setText(msgs.get(position).getMessageid());
			dateView.setText(msgs.get(position).getDate());
			msgView.setText(SmileysUtil.getInstance().getSmileSpan(msgs.get(position).getMessage()));
			return convertView;
		}
	}
	
	protected void onDestroy()
	{
		MessagesDao.getInstance().setMessage(1000, listMsg);
		super.onDestroy();
	}
}